﻿using hyjx;
using hyjx.bind;
using Hyjx.GanFengLogger.SqliteLog;
using GanFengLogViewer.Commands;
using GanFengLogViewer.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Threading;

namespace GanFengLogViewer.ViewModels
{
    public class MainWindowViewModel : BindableBase
    {
        public MainWindowViewModel()
        {
            Filter.SelectedInterface = Filter.InterfaceIds.First(p => p.Key == 201);
        }

        /// <summary>
        /// 过滤器
        /// </summary>
        public FilterModel Filter { get; } = new();
        /// <summary>
        /// 日志集
        /// </summary>
        public ObservableCollection<GanFengLogEntity> Logs { get; } = new();
        /// <summary>
        /// 分页器
        /// </summary>
        public PagorModel Pagor { get; } = new();

        private bool _isIdle = true;
        /// <summary>
        /// 是否空闲
        /// </summary>
        public bool IsIdle { get => _isIdle; set => SetProperty(ref _isIdle, value); }

        public void Window_Loaded(object sender, RoutedEventArgs e)
        {
            Filter.StartDate = DateTime.Now.AddDays(-1);
            Filter.EndDate = DateTime.Now;
            //await Task.Run(()=> Application.Current.Dispatcher.Invoke(()=> Filter.FilterCommand.Execute(this)));
            Filter.FilterCommand.Execute(this);
        }

        public void Logs_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            LogDetailWindow window = new();
            window.Owner = Application.Current.MainWindow;
            window.WindowStartupLocation = WindowStartupLocation.CenterOwner;
            LogDetailWindowViewModel vm = (LogDetailWindowViewModel)window.DataContext;
            ListView listview = (ListView)sender;
            if (listview.SelectedItem is GanFengLogEntity log)
            {
                vm.RequestUrl = log.RequestUrl;
                vm.RequestContent = log.RequestContent;
                vm.CreatedDatetime = log.CreatedDatetime;
                vm.ResponseContent = log.ResponseContent;
                vm.DeviceCode = log.DeviceCode;
                vm.InterfaceId = log.InterfaceId;
                vm.ExceptionDetail = log.ExceptionDetail;
                vm.Message = log.Message;
            }
            window.ShowDialog();
        }

        internal void GetLogs()
        {
            string dbFolder = $"{Environment.GetFolderPath(Environment.SpecialFolder.CommonDocuments)}\\hyjx";
            using GanFengLogDbContext db = new($"Filename={dbFolder}\\{App.DbName};Password={App.DbPassword}");
            if (db.Logs == null)
            {
                MessageBox.Show("日志数据不存在。", "数据库错误", MessageBoxButton.OK, MessageBoxImage.Error);
                Application.Current.Shutdown(0);
                return;
            }

            IsIdle = false;
            Pagor.RaiseCommandsCanExecute();
            Filter.FilterCommand.OnCanExecuteChanged();

            // 筛选
            IQueryable<GanFengLogEntity> query = db.Logs.AsQueryable();
            if (!string.IsNullOrEmpty(Filter.DeviceCode))
                query = query.Where(p => p.DeviceCode == Filter.DeviceCode);

            if (Filter.SelectedInterface.Key != 0)
                query = query.Where(p => p.InterfaceId == Filter.SelectedInterface.Key);

            if (Filter.StartDate != null)
                query = query.Where(p => p.CreatedDatetime >= Filter.StartDate);

            if (Filter.EndDate != null)
                query = query.Where(p => p.CreatedDatetime <= Filter.EndDate);

            // 排序
            query = LambdaHelper.Orderby(query, Filter.SelectedSortField.Key, Filter.SelectedOrderByField.Key);

            // 设置分页器
            Pagor.EntryAmount = query.Count();
            Pagor.TotalPage = (int)Math.Ceiling((decimal)Pagor.EntryAmount / Pagor.SelectedPageRows.Key);

            // 分页
            query = query.Skip((Pagor.CurrentPageNumber - 1) * Pagor.SelectedPageRows.Key).Take(Pagor.SelectedPageRows.Key);

            // 呈现
            Logs.Clear();
            foreach (var item in query)
            {
                Logs.Add(item);
            }

            if (!Logs.Any())
                Pagor.CurrentPageNumber = 0;

            IsIdle = true;
            Pagor.RaiseCommandsCanExecute();
            Filter.FilterCommand.OnCanExecuteChanged();
        }
    }
}
